const autoFocusUtils =  {
    autoFocusOnById:autoFocusOnById
}

function autoFocusOnById(page, eleId){
    let input = findFirstEnableInputById(eleId);
    if(input){
        focusOn(page, input);
    }
}

function findFirstEnableInputById(eleId){
    let ele = document.getElementById(eleId);
    return findFirstEnableInputByEle(ele);
}

function findFirstEnableInputByEle(ele){
    if(!ele){
        return;
    }
    let input = ele.querySelector('input:not([tabindex="-1"])');
    if(!input){
        input = findFirstEnableInputByEle(ele.nextElementSibling);
    }
    return input;
}

function focusOn(page, ele){
    if(ele){
        if(page.ViewModel){
            page.ViewModel.shouldAutoFocus = true;
        }
        ele.focus();
        setTimeout(() => {ele.select();});
        if(page.ViewModel){
            page.ViewModel.shouldAutoFocus = false;
        }
    }
}

export default autoFocusUtils;